package cn.jdemo.socket.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 一个socket请求阻塞了主线程，后续socket请求需要等待
 */
public class Demo01 {
    public static void main(String[] args) throws IOException {
        ServerSocket sSocket = new ServerSocket(8000);
        while (true){
            // 阻塞1:阻塞，直到建立连接
            Socket accept = sSocket.accept();
            handleSocket(accept);
        }
    }

    public static void handleSocket(Socket clientSocket) throws IOException {
        byte[] bytes = new byte[1024];
        while (true){
            // 阻塞2:阻塞，直到输入数据可用、检测到文件结尾或引发异常
            // (接收客户端的数据，阻塞方法，没有数据可读时就阻塞)
            int read = clientSocket.getInputStream().read(bytes);
            if (read != -1) {
                System.out.println("接收到客户端的数据：" + new String(bytes, 0, read));
            }
        }
        //服务器向客户端发送数据
        /*clientSocket.getOutputStream().write("ACK:HelloClient".getBytes());
        clientSocket.getOutputStream().flush();*/
    }
}
